package com.lry.web.rests;

import com.lry.web.user.entity.User;
import com.lry.web.user.service.UserService;
import org.apache.http.HttpRequest;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;
    @Autowired
    HttpServletRequest request;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //权限逻辑

        return null;
    }


    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //认证逻辑
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        // 从token中拿到用户名和密码
        String username = token.getUsername();
        String password = String.valueOf(token.getPassword());
        //在这做数据库查询验证账号密码是否正确
        AuthenticationInfo authcInfo = null;
        User user = userService.selectUser(new User(username, password));
        //模拟登录逻辑，正确返回AuthenticationInfo对象，错误返回null报错
        if(user!=null) {
            /**
             * 登录成功
             * 创建SimpleAuthenticationInfo的对象
             * 构造函数有3个参数
             * 参数1、用户名
             * 参数2、密码
             * 参数3、当前realm对象的类名
             */
            authcInfo = new SimpleAuthenticationInfo(username,password,this.getName());

            request.getSession().setAttribute("user", user);
        }
        return authcInfo;
    }
}